import { TITLE_COLOR } from './costant'

// 给颜色添加透明度 仅支持rgb、rgba、16进制
export function addOpacity(color, opacity = 0.2) {
	let rgbaColor = "";
	if (color.includes("#")) {
		// 如果是hex颜色
		let hex = color.replace("#", "");
		if (hex.length === 3) {
			// 处理3位hex颜色值
			hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
		}
		const r = parseInt(hex.substring(0, 2), 16);
		const g = parseInt(hex.substring(2, 4), 16);
		const b = parseInt(hex.substring(4, 6), 16);
		rgbaColor = `rgba(${r}, ${g}, ${b}, ${opacity})`;
	} else if (color.includes("rgb")) {
		// 如果是rgb或rgba颜色
		const rgbValues = color.match(/\d+/g);
		if (color.includes("rgba")) {
			// 如果已经是rgba，替换透明度
			rgbValues[3] = opacity;
		} else {
			// 如果是rgb，添加透明度
			rgbValues.push(opacity);
		}
		rgbaColor = `rgba(${rgbValues.join(", ")})`;
	} else {
		throw new Error("仅支持转换16进制、rgb、rgba的颜色值");
	}
	return rgbaColor;
}

// 标题
export const titleConfig = ({ title,titleColor, times, timesChange, duration, durationChange }) => {
	const result = [
		{
			key: 'a',
			value: {
				text: '',
				backgroundColor: titleColor,
				height: 18,
				width: 4,
			}
		},
		{
			key: 'b',
			value: {
				text: `${title}：`,
				fontWeight: 700,
				fontSize: 18,
				padding: [0, 0, 0, 8],
			}
		},
		{
			key: 'c',
			value: {
				text: `平均失效次数（次/年）：${times}`,
				padding: [0, 0, 0, 8],
				fontWeight: 400,
				fontSize: 18,
				color: TITLE_COLOR,
			}
		},
		{
			key: 'e',
			value: {
				text: `平均失效时长（小时/次）：${duration}`,
				padding: [0, 0, 0, 20],
				fontWeight: 400,
				fontSize: 18,
				color: TITLE_COLOR,
			}
		}
	]
	if (timesChange) {
		result.splice(3, 0, {
			key: 'd',
			value: {
				text: timesChange,
				padding: [0, 0, 0, 8],
				fontWeight: 400,
				fontSize: 18,
				color: "#0C9B4A",
			}
		})
	}
	if (durationChange) {
		result.push({
			key: 'f',
			value: {
				text: durationChange,
				padding: [0, 0, 0, 8],
				fontWeight: 400,
				fontSize: 18,
				color: "#0C9B4A",
			}
		})
	}
	return result
}

// 获取样式配置
export const getLegendStyle = (config) => {
	const arr = JSON.parse(JSON.stringify(config))
	const result = {}
	arr.forEach(item => {
		delete item.value.text;
		result[item.key] = item.value
	})
	return result
}
// 获取图例名称
export const getLegendName = (config) => {
	let result = ''
	config.forEach(item => {
		result += `{${item.key}|${item.value.text}}`
	})
	return result
}
